import React, { useState } from 'react';
import { Avatar, Dropdown, Space, Typography, Modal, Form, Input, Button, message, ConfigProvider } from 'antd';
import { UserOutlined, LogoutOutlined, EditOutlined, InfoCircleOutlined, LockOutlined, KeyOutlined, CopyOutlined } from '@ant-design/icons';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { changePassword, getCurrentUser, isAuthenticated, logout, updateProfile, generateAccessKey, GenerateAccessKeyResponse } from '@/services/api';
import { User } from '@/types/api';

const { Text } = Typography;

const UserProfile: React.FC = () => {
    const queryClient = useQueryClient();
    const navigate = useNavigate();
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
    const [isChangePasswordVisible, setIsChangePasswordVisible] = useState(false);
    const [isAccessKeyModalVisible, setIsAccessKeyModalVisible] = useState(false);
    const [accessKeyData, setAccessKeyData] = useState<GenerateAccessKeyResponse['data'] | null>(null);
    const [form] = Form.useForm();
    const [passwordForm] = Form.useForm();
    // 获取当前用户信息
    const { data: currentUser, isLoading } = useQuery<User>({
        queryKey: ['current-user'],
        queryFn: getCurrentUser,
        enabled: isAuthenticated(),
        staleTime: 5 * 60 * 1000,
    });

    // 登出mutation
    const logoutMutation = useMutation({
        mutationFn: logout,
        onSuccess: () => {
            queryClient.clear();
            message.success('已安全退出');
            navigate('/login');
        },
    });
    // 更新资料mutation
    const updateMutation = useMutation({
        mutationFn: updateProfile,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['current-user'] });
            message.success('个人信息更新成功');
            setIsEditModalVisible(false);
        },
        onError: (error: any) => {
            const errorData = error.response?.data;

            if (errorData?.errors && typeof errorData.errors === 'object') {
                // 处理字段级错误
                const formFields: any[] = [];
                let hasFieldErrors = false;

                Object.keys(errorData.errors).forEach((fieldName) => {
                    const errors = errorData.errors[fieldName];

                    if (Array.isArray(errors) && errors.length > 0) {
                        formFields.push({
                            name: fieldName,
                            errors: errors,
                        });
                        hasFieldErrors = true;
                    }
                });

                // 设置表单字段错误
                if (hasFieldErrors) {
                    form.setFields(formFields);
                }

                // 显示通用错误消息
                message.error(errorData.message || '更新失败');
            } else {
                // 其他类型的错误
                message.error(errorData?.message || '更新失败');
            }
        },
    }); // 修改密码mutation
    const changePasswordMutation = useMutation({
        mutationFn: changePassword,
        onSuccess: () => {
            message.success('密码修改成功');
            setIsChangePasswordVisible(false);
            passwordForm.resetFields();
        },
        onError: (error: any) => {
            const errorData = error.response?.data;

            if (errorData?.errors && typeof errorData.errors === 'object') {
                // 后端字段到前端字段的映射
                const fieldMapping: { [key: string]: string } = {
                    old_password: 'oldPassword',
                    new_password: 'newPassword',
                    confirm_password: 'confirmNewPassword',
                };

                // 处理字段级错误
                const formFields: any[] = [];
                let hasFieldErrors = false;

                Object.keys(errorData.errors).forEach((backendField) => {
                    const frontendField = fieldMapping[backendField] || backendField;
                    const errors = errorData.errors[backendField];

                    if (Array.isArray(errors) && errors.length > 0) {
                        formFields.push({
                            name: frontendField,
                            errors: errors,
                        });
                        hasFieldErrors = true;
                    }
                });

                // 设置表单字段错误
                if (hasFieldErrors) {
                    passwordForm.setFields(formFields);
                }

                // 显示通用错误消息
                message.error(errorData.message || '密码修改失败');
            } else {
                // 其他类型的错误
                message.error(errorData?.message || '修改密码失败');
            }
        },
    });

    // 生成访问令牌mutation
    const generateAccessKeyMutation = useMutation({
        mutationFn: generateAccessKey,
        onSuccess: (response) => {
            if (response.success && response.data) {
                setAccessKeyData(response.data);
                message.success('访问令牌生成成功');
            } else {
                message.error(response.message || '生成失败');
            }
        },
        onError: (error: any) => {
            const errorData = error.response?.data;
            message.error(errorData?.message || '生成访问令牌失败');
        },
    });

    const handleLogout = () => {
        Modal.confirm({
            title: '确认退出',
            content: '确定要退出登录吗？',
            onOk: () => logoutMutation.mutate(),
        });
    };

    const handleViewProfile = () => {
        navigate('/user-usage');
    };
    const handleEditProfile = () => {
        if (currentUser) {
            form.setFieldsValue({
                email: currentUser.email,
            });
            setIsEditModalVisible(true);
        }
    };
    const handleUpdateProfile = async () => {
        try {
            const values = await form.validateFields();
            if (currentUser) {
                updateMutation.mutate(values);
            }
        } catch (error) {
            console.error('表单验证失败:', error);
        }
    };

    const handleAccessManagement = () => {
        setIsAccessKeyModalVisible(true);
        setAccessKeyData(null); // 重置访问令牌数据
    };

    const handleGenerateAccessKey = () => {
        generateAccessKeyMutation.mutate();
    };

    const handleCopyAccessKey = () => {
        if (accessKeyData?.access_key) {
            navigator.clipboard
                .writeText(accessKeyData.access_key)
                .then(() => {
                    message.success('访问令牌已复制到剪贴板');
                })
                .catch(() => {
                    message.error('复制失败，请手动复制');
                });
        }
    };

    const handleCloseAccessKeyModal = () => {
        setIsAccessKeyModalVisible(false);
        setAccessKeyData(null);
    };

    const menuItems = [
        {
            key: 'profile',
            icon: <InfoCircleOutlined />,
            label: '个人信息',
            onClick: handleViewProfile,
        },
        {
            key: 'edit',
            icon: <EditOutlined />,
            label: '编辑资料',
            onClick: handleEditProfile,
        },
        {
            key: 'password',
            icon: <LockOutlined />,
            label: '修改密码',
            onClick: () => setIsChangePasswordVisible(true),
        },
        {
            key: 'access',
            icon: <KeyOutlined />,
            label: '访问管理',
            onClick: handleAccessManagement,
        },
        {
            type: 'divider' as const,
        },
        {
            key: 'logout',
            icon: <LogoutOutlined />,
            label: '退出登录',
            onClick: handleLogout,
        },
    ];

    if (!isAuthenticated()) {
        return (
            <Button type="primary" onClick={() => navigate('/login')}>
                登录
            </Button>
        );
    }

    if (isLoading) {
        return (
            <Space>
                <Avatar icon={<UserOutlined />} />
                <Text>加载中...</Text>
            </Space>
        );
    }
    if (!currentUser) {
        return (
            <Button type="primary" onClick={() => navigate('/login')}>
                登录
            </Button>
        );
    }

    // currentUser 直接是 User 对象，不需要 .data
    const user = currentUser;
    return (
        <>
            <Dropdown menu={{ items: menuItems }} trigger={['click']} placement="bottomRight">
                <Space
                    style={{
                        cursor: 'pointer',
                        padding: '4px 8px',
                        borderRadius: '6px',
                        transition: 'background-color 0.2s',
                    }}
                    size="small"
                >
                    <Avatar
                        size="small"
                        style={{
                            backgroundColor: user.is_active ? '#87d068' : '#ff4d4f',
                        }}
                        icon={<UserOutlined />}
                    />
                    <div
                        style={{
                            textAlign: 'left',
                            lineHeight: 1.2,
                            minWidth: '80px',
                        }}
                    >
                        <div
                            style={{
                                fontSize: '14px',
                                fontWeight: 500,
                                color: 'white',
                                marginBottom: '2px',
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                maxWidth: '120px',
                            }}
                        >
                            {user.username}
                        </div>
                        <div
                            style={{
                                fontSize: '12px',
                                color: 'white',
                                lineHeight: 1,
                            }}
                        >
                            {user.is_active ? '在线' : '离线'}
                        </div>
                    </div>
                </Space>
            </Dropdown>

            {/* 编辑资料模态框 */}
            <Modal
                title="编辑个人资料"
                open={isEditModalVisible}
                onOk={handleUpdateProfile}
                onCancel={() => {
                    setIsEditModalVisible(false);
                    form.resetFields();
                }}
                confirmLoading={updateMutation.isPending}
                okText="保存"
                cancelText="取消"
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                            { type: 'email', message: '请输入有效的邮箱地址' },
                            { max: 100, message: '邮箱地址最多100个字符' },
                        ]}
                    >
                        <Input placeholder="输入邮箱地址" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 修改密码模态框 */}
            <Modal
                title="修改密码"
                open={isChangePasswordVisible}
                onCancel={() => {
                    setIsChangePasswordVisible(false);
                    passwordForm.resetFields();
                }}
                confirmLoading={changePasswordMutation.isPending}
                okText="确认修改"
                cancelText="取消"
            >
                <Form form={passwordForm} layout="vertical">
                    <Form.Item name="oldPassword" label="当前密码" rules={[{ required: true, message: '请输入当前密码' }]}>
                        <Input.Password placeholder="请输入当前密码" />
                    </Form.Item>

                    <Form.Item
                        name="newPassword"
                        label="新密码"
                        rules={[
                            { required: true, message: '请输入新密码' },
                            { min: 6, message: '密码至少6个字符' },
                        ]}
                    >
                        <Input.Password placeholder="请输入新密码" />
                    </Form.Item>

                    <Form.Item
                        name="confirmNewPassword"
                        label="确认新密码"
                        dependencies={['newPassword']}
                        rules={[
                            { required: true, message: '请确认新密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('newPassword') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password placeholder="请确认新密码" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 访问管理弹窗 */}
            <style>
                {`
                    .access-key-modal .ant-modal-close {
                        color: #ffffff !important;
                    }
                    .access-key-modal .ant-modal-close:hover {
                        color: #ff4d4f !important;
                    }
                    .access-key-modal .ant-modal-close .ant-modal-close-x {
                        color: #ffffff !important;
                    }
                    .access-key-modal .ant-modal-close .ant-modal-close-x:hover {
                        color: #ff4d4f !important;
                    }
                `}
            </style>
            <ConfigProvider
                theme={{
                    components: {
                        Modal: {
                            contentBg: '#1f1f1f',
                            headerBg: '#1f1f1f',
                            titleColor: '#ffffff',
                            colorText: '#ffffff',
                        },
                        Button: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: '#ffffff',
                            colorPrimary: '#1890ff',
                            colorPrimaryHover: '#40a9ff',
                        },
                        Input: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: '#ffffff',
                            colorTextPlaceholder: 'rgba(255, 255, 255, 0.45)',
                        },
                    },
                }}
            >
                <Modal
                    title={<div style={{ color: '#ffffff', fontSize: '18px', fontWeight: 600 }}>🔑 访问管理</div>}
                    open={isAccessKeyModalVisible}
                    onCancel={handleCloseAccessKeyModal}
                    footer={null}
                    width={600}
                    centered
                    className="access-key-modal"
                    styles={{
                        header: {
                            background: '#1f1f1f',
                            borderBottom: '1px solid #303030',
                        },
                        body: {
                            background: '#1f1f1f',
                            padding: '24px',
                        },
                        mask: {
                            backdropFilter: 'blur(4px)',
                        },
                    }}
                    style={{
                        color: '#ffffff',
                    }}
                >
                    <div style={{ textAlign: 'center' }}>
                        {!accessKeyData ? (
                            // 未生成状态
                            <div>
                                <div
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.65)',
                                        fontSize: '14px',
                                        marginBottom: '24px',
                                        lineHeight: '1.6',
                                    }}
                                >
                                    请将此 API key 保存在安全且易于访问的地方。出于安全原因，你将无法通过API keys 管理界面再次查看它。如果你丢失了这个key，将需要重新创建。
                                </div>
                                <Button
                                    type="primary"
                                    size="large"
                                    icon={<KeyOutlined />}
                                    onClick={handleGenerateAccessKey}
                                    loading={generateAccessKeyMutation.isPending}
                                    style={{
                                        backgroundColor: '#1890ff',
                                        borderColor: '#1890ff',
                                        height: '48px',
                                        fontSize: '16px',
                                        fontWeight: 500,
                                        padding: '0 32px',
                                    }}
                                >
                                    点击生成令牌
                                </Button>
                            </div>
                        ) : (
                            // 已生成状态
                            <div>
                                <div
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.65)',
                                        fontSize: '14px',
                                        marginBottom: '24px',
                                        lineHeight: '1.6',
                                    }}
                                >
                                    请将此 API key 保存在安全且易于访问的地方。出于安全原因，你将无法通过API keys 管理界面再次查看它。如果你丢失了这个key，将需要重新创建。
                                </div>

                                {/* 访问令牌显示区域 */}
                                <div
                                    style={{
                                        backgroundColor: '#2a2a2a',
                                        border: '1px solid #434343',
                                        borderRadius: '8px',
                                        padding: '16px',
                                        marginBottom: '24px',
                                        position: 'relative',
                                    }}
                                >
                                    <div
                                        style={{
                                            color: '#ffffff',
                                            fontSize: '14px',
                                            fontFamily: 'monospace',
                                            wordBreak: 'break-all',
                                            lineHeight: '1.5',
                                            minHeight: '40px',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                        }}
                                    >
                                        {accessKeyData.access_key}
                                    </div>
                                </div>

                                {/* 按钮组 */}
                                <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
                                    <Button
                                        size="large"
                                        onClick={handleCloseAccessKeyModal}
                                        style={{
                                            backgroundColor: '#2a2a2a',
                                            borderColor: '#434343',
                                            color: '#ffffff',
                                            height: '40px',
                                            padding: '0 24px',
                                        }}
                                    >
                                        关闭
                                    </Button>
                                    <Button
                                        type="primary"
                                        size="large"
                                        icon={<CopyOutlined />}
                                        onClick={handleCopyAccessKey}
                                        style={{
                                            backgroundColor: '#1890ff',
                                            borderColor: '#1890ff',
                                            height: '40px',
                                            padding: '0 24px',
                                        }}
                                    >
                                        复制
                                    </Button>
                                    <Button
                                        type="primary"
                                        size="large"
                                        icon={<KeyOutlined />}
                                        onClick={handleGenerateAccessKey}
                                        loading={generateAccessKeyMutation.isPending}
                                        style={{
                                            backgroundColor: '#ff4d4f',
                                            borderColor: '#ff4d4f',
                                            height: '40px',
                                            padding: '0 24px',
                                        }}
                                    >
                                        重新生成令牌
                                    </Button>
                                </div>
                            </div>
                        )}
                    </div>
                </Modal>
            </ConfigProvider>
        </>
    );
};

export default UserProfile;
